package com.atguigu.lock;

import java.io.PrintStream;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: LDeng
 * @Date: 2021-09-05 12:13
 */

class Share22{
    private int number=0;

    private Lock lock=new ReentrantLock();

    private Condition condition=lock.newCondition();

    //+1
    public void incr() throws InterruptedException {
        lock.lock();
        try {
            //判断
            while(number!=0){
                condition.await();
            }
            //干活
            number++;
            System.out.println(Thread.currentThread().getName()+" :: "+number);
            //通知
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

    //-1
    public void decr() throws InterruptedException {
        lock.lock();
        try {
            while(number!=1){
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+" :: "+number);
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

}

public class ThreadDemo22 {

    public static void main(String[] args) {
        Share22 share22=new Share22();
        new Thread(()->{
            for (int i = 1; i < 10; i++) {
                try {
                    share22.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"AA").start();

        new Thread(()->{
            for (int i = 1; i < 10; i++) {
                try {
                    share22.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"BB").start();

        new Thread(()->{
            for (int i = 1; i < 10; i++) {
                try {
                    share22.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"CC").start();

        new Thread(()->{
            for (int i = 1; i < 10; i++) {
                try {
                    share22.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"DD").start();
    }

}
